accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = ''
flag = true;
now = timestamp = Date.parse(new Date()) / 1000;

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (xmlhttp!=null)
    {
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    g_object_name_type = 'random_name' ;//tt.value;
}

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000;
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback']
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    alert(g_object_name_type);
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}

function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}

function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };
    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

var img = new Array('jpg','jpeg','gif','png','bmp');
var imgLeng = img.length;
var newImgData = new Array();
for(var i=0; i<=imgLeng; i++){
    var val = img[i];
    if(val){
        var newImg = img[i].toUpperCase();
        newImgData.push(img[i]);
        newImgData.push(newImg);
    }

}
var imgStr = newImgData.toString();

//数组声明
nameArr = new Array();
var uploader = new plupload.Uploader({

    runtimes : 'html5,flash,silverlight,html4',
    browse_button : 'selectfiles',
    multi_selection: false,
    container: document.getElementById('container'),
    flash_swf_url : '/../static/js/ossupload/lib/plupload-2.1.2/js/Moxie.swf',
    silverlight_xap_url : '/../static/js/ossupload/ib/plupload-2.1.2/js/Moxie.xap',
    url : 'http://oss.aliyuncs.com',

    filters: {
        mime_types : [ //只允许上传图片和zip,rar文件
            { title : "Image files", extensions : imgStr },
            { title : "Video files", extensions : "avi,flv,mp4,wmv,mpeg,mov,mkv,f4v,m4v,rmvb,rm,3gp,dat,ts,mts,vob" },
            { title : "Music files", extensions : "mp3,m4a,wav,3gp,3gpp,aac,ogg" },
            { title : "Pdf files", extensions : "doc,docx,xls,xlsx,ppt,pptx,pdf,txt,htm,html,rar,zip,7z,jpg,gif,png,ico,jfif,tiff,tif,bmp,jpeg,jpe,mp3,mp4" }
        ],
        //max_file_size : '20mb', //最大只能上传10mb的文件
        max_file_size : '100mb', 
        prevent_duplicates : true //不允许选取重复文件
    },

    init: {

        PostInit: function() {

            document.getElementById('ossfile').innerHTML = '';
            document.getElementById('postfiles').onclick = function() {
                if ( ! $('#ossfile>div').html() ) {
                    alert("请选择要上传的文件");
                    return;
                }
                if (flag){
                    flag = false;
                    set_upload_param(uploader, '', false);
                }else {
                    alert("正在上传中,请勿重复点击,请稍等...");
                }

                return false;
            };
        },

        FilesAdded: function(up, files) {
            var fileType = document.getElementById('ossfile').getAttribute('attr_type');
            var type = 'img';
            if ( fileType ) {
                type = fileType;
            }
            var fileTypeData = new Array();
            if ( type.toLowerCase() == 'img' ) {
                fileTypeData = newImgData;
            } else if( type.toLowerCase() == 'video' ){
                fileTypeData = new Array('avi','flv','mp4','wmv','mpeg','mov','mkv','f4v','m4v','rmvb','rm','3gp','dat','ts','mts','vob');
            } else if( type.toLowerCase() == 'pdf' ){
                fileTypeData = new Array('doc','docx','xls','xlsx','ppt','pptx','pdf','txt','htm','html','rar','zip','7z','jpg','gif','png','ico','jfif','tiff','tif','bmp','jpeg','jpe','mp3','mp4');
            } else {
                fileTypeData = new Array('mp3','m4a','wav','3gp','3gpp','aac','ogg');
            }

            

            plupload.each(files, function(file) {
                var filed =  file.name;
                //存储名字
                nameArr[nameArr.length] = filed;
                //console.log(filed);
                filed = filed.substring(filed.lastIndexOf(".")+1,filed.length);
                var isTrue = fileTypeData.indexOf(filed);

                if ( isTrue == -1 ) {
                    //错误
                    var typeFiled = fileTypeData.join(',')
                    alert('文件类型错误,支持上传扩展名为'+typeFiled);
                    return;
                }
                document.getElementById('ossfile').innerHTML += '<div style="text-align:center;" id="' + file.id + '">' + file.name + ' &nbsp;&nbsp;(' + plupload.formatSize(file.size) + ')<b></b>'
                    +'<div class="progress" style="width:100%"><div class="progress-bar" style="width: 0%"></div></div>'
                    +'</div>';
            });

            localStorage.setItem('file_name_json',JSON.stringify(nameArr));
            var read = JSON.parse(localStorage.getItem('file_name_json'));

            console.log(read);
            console.log(localStorage.getItem('file_name_json'));
        },

        BeforeUpload: function(up, file) {
            check_object_radio();
            set_upload_param(up, file.name, true);
        },

        UploadProgress: function(up, file) {
            var d = document.getElementById(file.id);
            d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            var prog = d.getElementsByTagName('div')[0];
            var progBar = prog.getElementsByTagName('div')[0]
            //progBar.style.width= 2*file.percent+'px';
			progBar.style.width= '100%';
            progBar.setAttribute('aria-valuenow', file.percent);
        },

        FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '&nbsp;&nbsp;上传成功<p style="float:none;width:100%">' + get_uploaded_object_name(file.name)+'</p>';
            }
            else
            {
                document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
            }
            flag = true;
        },

        Error: function(up, err) {
            if (err.code == -600) {
                //document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,最大只能上传20M"));
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件太大了,最大只能上传100M"));
            }
            else if (err.code == -601) {
                document.getElementById('console').appendChild(document.createTextNode("\n选择的文件后缀不对,可以根据应用情况，在upload.js进行设置可允许的上传文件类型"));
            }
            else if (err.code == -602) {
                document.getElementById('console').appendChild(document.createTextNode("\n这个文件已经上传过一遍了"));
            }
            else
            {
                document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
            }
            flag = true;
        }
    }
});

uploader.init();
